package com.example.iceman.stepcounterapp;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.iceman.stepcounterapp.db.StepDataBase;
import com.example.iceman.stepcounterapp.widget.CircleShapeView;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Calendar;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by iceman on 16/3/10 11:35
 * 邮箱：xubin865@pingan.com.cn
 */
public class StepCounterMainActivity extends FragmentActivity {
    @Bind(R.id.circle)
    CircleShapeView circle;
    @Bind(R.id.currentSteps)
    TextView currentSteps;
    @Bind(R.id.step_type)
    TextView stepType;
    @Bind(R.id.heat)
    TextView heat;
    @Bind(R.id.time)
    TextView time;
    @Bind(R.id.step_record_frame)
    LinearLayout stepHistoryFrame;
    @Bind(R.id.history_button)
    ImageView historyButton;
    @Bind(R.id.setting_button)
    ImageView settingButton;
    @Bind(R.id.target_step_text)
    TextView targetStepText;

    private int targetStep = 10000;

    private int currentStepInt;

    private Handler refreshHandler = new Handler() {
    };

    private Runnable refreshStepRunnable = new Runnable() {
        @Override
        public void run() {
            showCurrentSteps();
            refreshHandler.postDelayed(refreshStepRunnable, 500);
        }
    };

    private void showCurrentSteps() {
        int current = 0;
        if (mIAIDLService != null) {
            try {
                current = mIAIDLService.getCurrentSteps();

            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        if (current != 0 && currentStepInt != current) {
            currentStepInt = current;
            currentSteps.setText(String.valueOf(current));
            heat.setText(String.valueOf(StepUtil.calculateHeat(current)));
            time.setText(String.valueOf(StepUtil.calculateTime(current)));
            circle.setCurrentPercent(current * 100 / targetStep);
        }

    }


    IStepCountInterface mIAIDLService;

    private ServiceConnection conn = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            System.out.println("service连接");
            mIAIDLService = IStepCountInterface.Stub.asInterface(service);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            System.out.println("service断开连接");
            mIAIDLService = null;
        }

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.step_counter_layout);
        ButterKnife.bind(this);
        startStepService();
        bindStepService();
        refreshHandler.post(refreshStepRunnable);
        initView();
        initData();
        new Thread() {
            @Override
            public void run() {
                super.run();
                getWeatherInfo();
            }
        }.start();
    }

    private void getWeatherInfo() {
        //2ceafc6dd985b2b399e1fcb6af187f80

        String httpUrl = "https://api.heweather.com/x3/weather";
        String httpArg = "city=" + "shanghai";
        String keyString = "&key=d8846800b92f4ee7bfb09535f3939462";

        BufferedReader reader = null;
        String result = null;
        StringBuffer sbf = new StringBuffer();
        String urlString = httpUrl + "?" + httpArg + keyString;

        try {
            URL url = new URL(urlString);
            HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            InputStream is = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sbf.append(strRead);
                sbf.append("\r\n");
            }
            reader.close();
            result = sbf.toString();
            System.out.println(result);

            JSONObject object = new JSONObject(result);
            JSONArray weatherArray = object.getJSONArray("HeWeather data service 3.0");
            JSONObject weatherObject = weatherArray.getJSONObject(0);
            JSONObject now = weatherObject.getJSONObject("now");
            JSONObject cond = now.getJSONObject("cond");
//            String weathercode = cond.getString("code");
            String weatherString = cond.getString("txt");


            JSONObject aqi = weatherObject.getJSONObject("aqi");
            JSONObject city = aqi.getJSONObject("city");
            String qlty = city.getString("qlty");


            System.out.println("最终天气信息:" + weatherString + ":空气质量" + qlty);


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initData() {
        Calendar calendar = Calendar.getInstance();
        addLastMonthStep(stepHistoryFrame, calendar);
        addLastWeekStep(stepHistoryFrame);
        addTodayStep(stepHistoryFrame, calendar);
    }

    private void addLastMonthStep(ViewGroup viewGroup, Calendar calendar) {
        int year, month;
        year = calendar.get(Calendar.YEAR);
        int currentMonth = calendar.get(Calendar.MONTH) + 1;
        if (currentMonth == 1) {
            month = 12;
            year--;
        } else {
            month = currentMonth - 1;
        }

        int count = StepSaveManager.getInstance().getStepTotalByMonth(year, month);

        View view = getLayoutInflater().inflate(R.layout.step_history_item, null);
        TextView title = (TextView) view.findViewById(R.id.title);
        TextView content = (TextView) view.findViewById(R.id.content);
        title.setText(getString(R.string.step_history_title, "上个月", String.valueOf(count)));

        String timeStr = String.format(String.valueOf(StepUtil.calculateTime(count)), "%.1f");
        String heatStr = String.format(String.valueOf(StepUtil.calculateHeat(count)), "%.1f");

        content.setText(getString(R.string.step_history_content, timeStr, heatStr));
        viewGroup.addView(view);
    }

    private void addLastWeekStep(ViewGroup viewGroup) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_YEAR, -7);
        int year, week;
        year = calendar.get(Calendar.YEAR);
        week = calendar.get(Calendar.WEEK_OF_YEAR);

        int count = StepSaveManager.getInstance().getStepTotalByWeek(year, week);

        View view = getLayoutInflater().inflate(R.layout.step_history_item, null);
        TextView title = (TextView) view.findViewById(R.id.title);
        TextView content = (TextView) view.findViewById(R.id.content);
        title.setText(getString(R.string.step_history_title, "上周", String.valueOf(count)));

        String timeStr = String.format(String.valueOf(StepUtil.calculateTime(count)), "%.1f");
        String heatStr = String.format(String.valueOf(StepUtil.calculateHeat(count)), "%.1f");

        content.setText(getString(R.string.step_history_content, timeStr, heatStr));
        viewGroup.addView(view);
    }

    private void addTodayStep(ViewGroup viewGroup, Calendar calendar) {
        int year, day;
        year = calendar.get(Calendar.YEAR);
        day = calendar.get(Calendar.DAY_OF_YEAR);

        ArrayList<StepDataBase> todaySteps = StepSaveManager.getInstance().getStepDataByDay(year, day);
        for (StepDataBase entity : todaySteps) {
            View view = getLayoutInflater().inflate(R.layout.step_history_item, null);
            TextView title = (TextView) view.findViewById(R.id.title);
            TextView content = (TextView) view.findViewById(R.id.content);
            title.setText(getString(R.string.step_history_title, entity.hour + ":00", String.valueOf(entity.count)));

            String timeStr = String.format(String.valueOf(StepUtil.calculateTime(entity.count)), "%.1f");
            String heatStr = String.format(String.valueOf(StepUtil.calculateHeat(entity.count)), "%.1f");

            content.setText(getString(R.string.step_history_content, timeStr, heatStr));
            viewGroup.addView(view);
        }


    }

    private void initView() {
//        LayoutInflater inflater = getLayoutInflater();
//        for (int i = 0; i < 3; i++) {
//            View view = inflater.inflate(R.layout.step_history_item, null);
//            TextView title = (TextView) view.findViewById(R.id.title);
//            TextView content = (TextView) view.findViewById(R.id.content);
//            title.setText(getString(R.string.step_history_title, "上星期", "1555"));
//            content.setText(getString(R.string.step_history_content, "33", "1200"));
//            stepHistoryFrame.addView(view);
//        }
        targetStepText.setText("目标:" + targetStep);
        circle.setOnclickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(StepCounterMainActivity.this, CurrentStepDetailActivity.class));
            }
        });
        historyButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(StepCounterMainActivity.this, HistoryStepDetailActivity.class));
            }
        });
    }

    private void startStepService() {
        Intent intent = new Intent();
        intent.setAction("com.followup.action.AIDL_SERVICE");
        intent.setPackage(getPackageName());
        startService(intent);
    }

    private void bindStepService() {
        Intent intent = new Intent();
        intent.setAction("com.followup.action.AIDL_SERVICE");
        intent.setPackage(getPackageName());
//        Intent intent = new Intent("com.followup.action.AIDL_SERVICE");
        bindService(intent, conn, Context.BIND_AUTO_CREATE);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mIAIDLService != null) {
            unbindService(conn);
        }
        refreshHandler.removeCallbacks(refreshStepRunnable);
    }
}
